import { useUserStore } from "@/stores";
import { useStorage } from "./storage";

let baseHOST='https://saas.kf.renloong.com/app/ycFlyingChess/';
let baseURL=`${baseHOST}api/`;
// #ifdef H5
import system from './h5/system';
// #endif
// #ifdef MP-WEIXIN
import system from './mp-weixin/system';
// #endif
if(system.isProd()){
	baseHOST=`${system.host()}/app/ycFlyingChess/`;
	baseURL=`${system.host()}/app/ycFlyingChess/api/`;
}
const RequestHeaders=(options?:any)=>{
	const header:any={};
	const {getToken,hasLogin}=useUserStore();
	if(hasLogin()){
		header['Authorization']=getToken();
	}
	if(options&&options.header){
		for (let x in options.header) {
			header[x]=options.header[x]
		}
	}
	const storeage=useStorage();
	const appid=system.appid();
	if(appid){
		header['Appid']=appid;
		const icode=storeage.get('ICODE.'+appid);
		if(icode){
			header['Icode']=icode;
		}
		const PUID=storeage.get('PUID.'+appid);
		if(PUID){
			header['Puid']=PUID;
		}
	}
	return header;
}
export const $http = {
    ResponseCode: {
        SUCCESS: 200,
        NEED_LOGIN: 12000,
        PAY_SUCCESS: 9000,
		PAY_NOTPAY: 11000,
		NEED_PAY:60000
    },
    baseURL,
	baseHOST,
    get: (url:string,options?:any):Promise<any>=>{
		return new Promise((resolve,reject)=>{
			uni.request({
				...options,
				header:RequestHeaders(options),
				url:baseURL+url,
				success:(res:any)=>{
					if(res.statusCode===200){
						resolve(res.data);
					}else{
						reject(res);
					}
				},
				fail:(err:any)=>{
					reject(err);
				},
				complete:()=>{}
			})
		})
	},
    post: (url:string,options:any):Promise<any>=>{
		return new Promise((resolve,reject)=>{
			uni.request({
				...options,
				header:RequestHeaders(options),
				url:baseURL+url,
				method:'POST',
				success:(res:any)=>{
					if(res.statusCode===200){
						resolve(res.data);
					}else{
						reject(res);
					}
				},
				fail:(err:any)=>{
					reject(err);
				},
				complete:()=>{}
			})
		})
	},
	upload:(url:string,options:any): Promise<any>=>{
		return new Promise((resolve,reject)=>{
				uni.uploadFile({
				...options,
				header:RequestHeaders(options),
				url:baseURL+url,
				success:(res:any)=>{
					if(res.statusCode===200){
						try{
							const data=JSON.parse(res.data);
							resolve(data);
						}catch(e){
							reject(res);
						}
					}else{
						reject(res);
					}
				},
				fail:(err:any)=>{
					reject(err);
				},
			})
		})
	}
}